package com.website.dayouziblog.job;

import com.alibaba.fastjson.JSONObject;
import com.website.dayouziblog.mapper.dayouziblog.ArticleMapper;
import com.website.dayouziblog.mapper.informationSchema.ArticleTotalsMapper;
import com.website.dayouziblog.model.DO.ArticleDO;
import com.website.dayouziblog.model.VO.ArticleVO;
import com.website.dayouziblog.utils.RedisUtil;
import com.website.dayouziblog.utils.TimeUtil;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 文章内容热点数据定时任务
 */
@Component
public class ArticleHotInfoJob extends QuartzJobBean {


    @Resource
    private ArticleTotalsMapper articleTotalsMapper;

    @Resource
    private ArticleMapper articleMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String key = jobDataMap.get("key").toString();
        //获取热点文章列表
        List<ArticleDO> hotArticle = articleMapper.findHotArticle();
        for (ArticleDO articleDO : hotArticle) {
            ArticleVO articleVO = JSONObject.parseObject(JSONObject.toJSONString(articleDO), ArticleVO.class);
            //存入info
            redisTemplate.opsForHash().put("Article:HotInfo", JSONObject.toJSONString(articleVO.getId()),
                    JSONObject.toJSONString(articleVO));
            //存入排序
            Double score = Double.valueOf(TimeUtil.dateTotimeStamp(articleVO.getPubtime()));
            redisTemplate.opsForZSet().add("Article:Order", JSONObject.toJSONString(articleVO.getId()), score);
        }
        //设置过期时间
        redisTemplate.expire("Article:HotInfo", 1800, TimeUnit.SECONDS);
        redisTemplate.expire("Article:Order", 1800, TimeUnit.SECONDS);
    }
}
